// DeepSeek API 配置
const deepseekConfig = {
    apiKey: 'sk-3b3510d93da74a29b2b36d5f35a43d15',
    apiUrl: 'https://api.deepseek.com/chat/completions',
    model: 'deepseek-chat'
};

// 游戏配置
const config = {
    canvasWidth: 800,
    canvasHeight: 600,
    playerSpeed: 5,
    enemySpeed: 2,
    bulletSpeed: 10,
    enemySpawnRate: 1500, // 毫秒
    maxEnemies: 5,
    playerSize: 20,
    enemySize: 20,
    bulletSize: 5,
    weaponRange: 300,
    initialAmmo: 30,
    maxAmmo: 30,
    reloadTime: 2000 // 毫秒
};

// 游戏状态
let gameState = {
    isRunning: false,
    score: 0,
    lives: 3,
    ammo: config.initialAmmo,
    lastEnemySpawn: 0,
    lastReloadTime: 0,
    isReloading: false,
    mouseX: 0,
    mouseY: 0,
    startTime: 0,
    endTime: 0,
    shotsFired: 0,
    enemiesKilled: 0
};

// 游戏对象
let player = {
    x: config.canvasWidth / 2,
    y: config.canvasHeight / 2,
    direction: 0, // 弧度
    isMoving: {
        up: false,
        down: false,
        left: false,
        right: false
    }
};

let enemies = [];
let bullets = [];
let keys = {};

// DOM元素
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreElement = document.getElementById('score');
const livesElement = document.getElementById('lives');
const ammoElement = document.getElementById('ammo');
const maxAmmoElement = document.getElementById('maxAmmo');
const startScreen = document.getElementById('startScreen');
const gameOverScreen = document.getElementById('gameOver');
const finalScoreElement = document.getElementById('finalScore');

// 创建评价结果元素
let feedbackElement = null;

// 初始化游戏
function initGame() {
    // 设置画布尺寸
    canvas.width = config.canvasWidth;
    canvas.height = config.canvasHeight;
    
    // 绑定事件监听器
    document.addEventListener('keydown', handleKeyDown);
    document.addEventListener('keyup', handleKeyUp);
    canvas.addEventListener('mousemove', handleMouseMove);
    canvas.addEventListener('mousedown', handleMouseDown);
    
    // 更新UI
    updateUI();
    
    // 开始游戏循环
    requestAnimationFrame(gameLoop);
}

// 重置游戏
function resetGame() {
    gameState = {
        isRunning: true,
        score: 0,
        lives: 3,
        ammo: config.initialAmmo,
        lastEnemySpawn: Date.now(),
        lastReloadTime: 0,
        isReloading: false,
        mouseX: 0,
        mouseY: 0,
        startTime: Date.now(),
        endTime: 0,
        shotsFired: 0,
        enemiesKilled: 0
    };
    
    player = {
        x: config.canvasWidth / 2,
        y: config.canvasHeight / 2,
        direction: 0,
        isMoving: {
            up: false,
            down: false,
            left: false,
            right: false
        }
    };
    
    enemies = [];
    bullets = [];
    
    startScreen.style.display = 'none';
    gameOverScreen.style.display = 'none';
    
    // 移除之前的评价结果
    if (feedbackElement) {
        feedbackElement.remove();
        feedbackElement = null;
    }
    
    updateUI();
}

// 更新UI
function updateUI() {
    scoreElement.textContent = gameState.score;
    livesElement.textContent = gameState.lives;
    ammoElement.textContent = gameState.ammo;
    maxAmmoElement.textContent = config.maxAmmo;
    finalScoreElement.textContent = gameState.score;
}

// 处理键盘按下
function handleKeyDown(e) {
    keys[e.key.toLowerCase()] = true;
    
    // 空格键开始游戏
    if (e.key === ' ' && !gameState.isRunning) {
        resetGame();
    }
    
    // R键重新开始或换弹
    if (e.key.toLowerCase() === 'r') {
        if (!gameState.isRunning) {
            resetGame();
        } else if (!gameState.isReloading && gameState.ammo < config.maxAmmo) {
            reload();
        }
    }
}

// 处理键盘释放
function handleKeyUp(e) {
    keys[e.key.toLowerCase()] = false;
}

// 处理鼠标移动
function handleMouseMove(e) {
    const rect = canvas.getBoundingClientRect();
    gameState.mouseX = e.clientX - rect.left;
    gameState.mouseY = e.clientY - rect.top;
    
    // 更新玩家方向
    player.direction = Math.atan2(
        gameState.mouseY - player.y,
        gameState.mouseX - player.x
    );
}

// 处理鼠标按下
function handleMouseDown(e) {
    if (gameState.isRunning && gameState.ammo > 0 && !gameState.isReloading) {
        shoot();
    }
}

// 换弹
function reload() {
    gameState.isReloading = true;
    gameState.lastReloadTime = Date.now();
    
    // 2秒后完成换弹
    setTimeout(() => {
        gameState.ammo = config.maxAmmo;
        gameState.isReloading = false;
        updateUI();
    }, config.reloadTime);
}

// 射击
function shoot() {
    const bullet = {
        x: player.x,
        y: player.y,
        direction: player.direction,
        distance: 0
    };
    
    bullets.push(bullet);
    gameState.ammo--;
    gameState.shotsFired++;
    updateUI();
}

// 生成敌人
function spawnEnemy() {
    if (enemies.length >= config.maxEnemies) return;
    
    // 随机生成敌人位置（在屏幕边缘）
    const spawnSide = Math.floor(Math.random() * 4); // 0:上, 1:右, 2:下, 3:左
    let x, y;
    
    switch (spawnSide) {
        case 0: // 上
            x = Math.random() * config.canvasWidth;
            y = -config.enemySize;
            break;
        case 1: // 右
            x = config.canvasWidth + config.enemySize;
            y = Math.random() * config.canvasHeight;
            break;
        case 2: // 下
            x = Math.random() * config.canvasWidth;
            y = config.canvasHeight + config.enemySize;
            break;
        case 3: // 左
            x = -config.enemySize;
            y = Math.random() * config.canvasHeight;
            break;
    }
    
    enemies.push({
        x: x,
        y: y,
        health: 1
    });
}

// 更新玩家位置
function updatePlayer() {
    // 移动控制
    if (keys['w'] || keys['arrowup']) {
        player.y = Math.max(0, player.y - config.playerSpeed);
    }
    if (keys['s'] || keys['arrowdown']) {
        player.y = Math.min(config.canvasHeight, player.y + config.playerSpeed);
    }
    if (keys['a'] || keys['arrowleft']) {
        player.x = Math.max(0, player.x - config.playerSpeed);
    }
    if (keys['d'] || keys['arrowright']) {
        player.x = Math.min(config.canvasWidth, player.x + config.playerSpeed);
    }
}

// 更新敌人
function updateEnemies() {
    for (let i = enemies.length - 1; i >= 0; i--) {
        const enemy = enemies[i];
        
        // 计算敌人朝向玩家的方向
        const direction = Math.atan2(
            player.y - enemy.y,
            player.x - enemy.x
        );
        
        // 移动敌人
        enemy.x += Math.cos(direction) * config.enemySpeed;
        enemy.y += Math.sin(direction) * config.enemySpeed;
        
        // 检测敌人是否到达玩家位置
        const distance = Math.sqrt(
            Math.pow(enemy.x - player.x, 2) + Math.pow(enemy.y - player.y, 2)
        );
        
        if (distance < config.playerSize) {
            // 敌人与玩家碰撞
            gameState.lives--;
            enemies.splice(i, 1);
            updateUI();
            
            if (gameState.lives <= 0) {
                gameOver();
            }
        }
    }
}

// 更新子弹
function updateBullets() {
    for (let i = bullets.length - 1; i >= 0; i--) {
        const bullet = bullets[i];
        
        // 移动子弹
        bullet.x += Math.cos(bullet.direction) * config.bulletSpeed;
        bullet.y += Math.sin(bullet.direction) * config.bulletSpeed;
        bullet.distance += config.bulletSpeed;
        
        // 检查子弹是否超出射程
        if (bullet.distance > config.weaponRange || 
            bullet.x < 0 || bullet.x > config.canvasWidth || 
            bullet.y < 0 || bullet.y > config.canvasHeight) {
            bullets.splice(i, 1);
            continue;
        }
        
        // 检查子弹是否击中敌人
        for (let j = enemies.length - 1; j >= 0; j--) {
            const enemy = enemies[j];
            const distance = Math.sqrt(
                Math.pow(bullet.x - enemy.x, 2) + Math.pow(bullet.y - enemy.y, 2)
            );
            
            if (distance < config.enemySize / 2 + config.bulletSize) {
                // 击中敌人
            enemies.splice(j, 1);
            bullets.splice(i, 1);
            gameState.score += 10;
            gameState.enemiesKilled++;
            updateUI();
            break;
            }
        }
    }
}

// 游戏结束
function gameOver() {
    gameState.isRunning = false;
    gameState.endTime = Date.now();
    gameOverScreen.style.display = 'block';
    
    // 获取游戏表现评价
    getGameFeedback();
}

// 绘制像素风格的矩形
function drawPixelRect(x, y, width, height, color) {
    ctx.fillStyle = color;
    // 使用整数坐标以保持像素风格
    ctx.fillRect(Math.floor(x), Math.floor(y), width, height);
}

// 绘制玩家
function drawPlayer() {
    // 绘制玩家主体
    drawPixelRect(
        player.x - config.playerSize / 2,
        player.y - config.playerSize / 2,
        config.playerSize,
        config.playerSize,
        '#00ff00'
    );
    
    // 绘制方向指示器
    const indicatorLength = config.playerSize;
    const indicatorX = player.x + Math.cos(player.direction) * indicatorLength;
    const indicatorY = player.y + Math.sin(player.direction) * indicatorLength;
    
    ctx.strokeStyle = '#ff0000';
    ctx.lineWidth = 2;
    ctx.beginPath();
    ctx.moveTo(player.x, player.y);
    ctx.lineTo(indicatorX, indicatorY);
    ctx.stroke();
}

// 绘制敌人
function drawEnemies() {
    enemies.forEach(enemy => {
        drawPixelRect(
            enemy.x - config.enemySize / 2,
            enemy.y - config.enemySize / 2,
            config.enemySize,
            config.enemySize,
            '#ff0000'
        );
    });
}

// 绘制子弹
function drawBullets() {
    bullets.forEach(bullet => {
        drawPixelRect(
            bullet.x - config.bulletSize / 2,
            bullet.y - config.bulletSize / 2,
            config.bulletSize,
            config.bulletSize,
            '#ffff00'
        );
    });
}

// 绘制换弹指示器
function drawReloadIndicator() {
    if (gameState.isReloading) {
        const reloadProgress = (Date.now() - gameState.lastReloadTime) / config.reloadTime;
        const barWidth = 100;
        const barHeight = 10;
        const x = 10;
        const y = 60;
        
        // 绘制背景
        drawPixelRect(x, y, barWidth, barHeight, '#333333');
        
        // 绘制进度条
        const progressWidth = Math.min(barWidth, barWidth * reloadProgress);
        drawPixelRect(x, y, progressWidth, barHeight, '#00ff00');
        
        ctx.fillStyle = '#ffffff';
        ctx.font = '12px Courier New';
        ctx.fillText('换弹中...', x + barWidth + 10, y + barHeight - 2);
    }
}

// 渲染游戏
function render() {
    // 清空画布
    ctx.fillStyle = '#2a2a2a';
    ctx.fillRect(0, 0, config.canvasWidth, config.canvasHeight);
    
    // 绘制网格（像素风格）
    ctx.strokeStyle = '#333333';
    ctx.lineWidth = 1;
    for (let i = 0; i < config.canvasWidth; i += 20) {
        ctx.beginPath();
        ctx.moveTo(i, 0);
        ctx.lineTo(i, config.canvasHeight);
        ctx.stroke();
    }
    for (let i = 0; i < config.canvasHeight; i += 20) {
        ctx.beginPath();
        ctx.moveTo(0, i);
        ctx.lineTo(config.canvasWidth, i);
        ctx.stroke();
    }
    
    if (gameState.isRunning) {
        // 绘制游戏对象
        drawPlayer();
        drawEnemies();
        drawBullets();
        drawReloadIndicator();
    }
}

// 游戏主循环
function gameLoop(timestamp) {
    if (gameState.isRunning) {
        // 生成敌人
        const currentTime = Date.now();
        if (currentTime - gameState.lastEnemySpawn > config.enemySpawnRate) {
            spawnEnemy();
            gameState.lastEnemySpawn = currentTime;
        }
        
        // 更新游戏状态
        updatePlayer();
        updateEnemies();
        updateBullets();
    }
    
    // 渲染画面
    render();
    
    // 继续游戏循环
    requestAnimationFrame(gameLoop);
}

// 获取游戏表现评价
async function getGameFeedback() {
    // 计算游戏统计数据
    const survivalTime = Math.round((gameState.endTime - gameState.startTime) / 1000); // 秒
    const accuracy = gameState.shotsFired > 0 ? 
        Math.round((gameState.enemiesKilled / gameState.shotsFired) * 100) : 0;
    const killRate = survivalTime > 0 ? 
        (gameState.enemiesKilled / survivalTime).toFixed(2) : 0;
    
    // 构建评价请求
    const messages = [
        {
            role: "system",
            content: "你是一位专业但很幽默的游戏评论家，擅长用搞笑、调侃的方式评价玩家的游戏表现。请基于提供的游戏统计数据，从多个角度给出有趣的评价，包括但不限于：分数、命中率、生存时间、击杀效率等。评价要幽默风趣，带有一点调侃但又不失鼓励。请用中文回复，风格活泼，不超过100字。"
        },
        {
            role: "user",
            content: `请评价这位玩家的像素射击游戏表现：\n得分：${gameState.score}\n存活时间：${survivalTime}秒\n击杀敌人：${gameState.enemiesKilled}个\n射击次数：${gameState.shotsFired}次\n命中率：${accuracy}%\n每秒击杀：${killRate}个`
        }
    ];
    
    try {
        // 调用DeepSeek API
        const response = await fetch(deepseekConfig.apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${deepseekConfig.apiKey}`
            },
            body: JSON.stringify({
                model: deepseekConfig.model,
                messages: messages,
                stream: false
            })
        });
        
        if (!response.ok) {
            throw new Error(`API调用失败: ${response.status}`);
        }
        
        const data = await response.json();
        const feedback = data.choices[0].message.content;
        
        // 显示评价结果
        showFeedback(feedback);
    } catch (error) {
        console.error('获取游戏评价失败:', error);
        showFeedback('系统繁忙，无法获取评价。不过我猜你玩得很6！');
    }
}

// 显示游戏评价
function showFeedback(feedback) {
    // 创建评价元素
    feedbackElement = document.createElement('div');
    feedbackElement.id = 'gameFeedback';
    feedbackElement.style.cssText = `
        position: absolute;
        top: 70%;
        left: 50%;
        transform: translate(-50%, -50%);
        background-color: rgba(0, 0, 0, 0.9);
        padding: 20px;
        border-radius: 10px;
        text-align: center;
        z-index: 25;
        border: 2px solid #00ff00;
        max-width: 600px;
        color: #ffffff;
        font-family: 'Courier New', monospace;
        font-size: 16px;
        line-height: 1.5;
    `;
    
    feedbackElement.textContent = feedback;
    document.body.appendChild(feedbackElement);
}

// 启动游戏
initGame();